
import java.sql.*;

public class CSVConn {
	Connection conn;
	Statement stmt;
	boolean connected;
	ResultSet results;
	String path;
	
	public CSVConn(String _path){
		connected = false;
		path = _path;
	}
	
	public void setPath(String _path) {
		path = _path;
	}
	
	/* Try to set up connection to a directory containing CSV files. 
	 * Return 0 upon failure. 
	 */
	private int connect(){
		if(connected)
			disconnect();
		
		try
		{
			// load the driver into memory
			Class.forName("org.relique.jdbc.csv.CsvDriver");

			// create a connection. The first command line parameter is assumed to
			//  be the directory in which the .csv files are held
			conn = DriverManager.getConnection("jdbc:relique:csv:"+ path);

			return 1;
		}
		catch(Exception e)
		{
			System.out.println("Error in connect()-> " + e);
			// failure!
			return 0; 
		}
		
	}
	
	/* Get current resultset. May be empty.
	 */
	public ResultSet getResults() {
		return results;		
	}
	
	/* Try to execute a sql query. 
	 * Return 0 upon failure. 
	 */
	public int query(String query) {
		connect();
		System.out.println("Executing query: " + query);
		try
		{
			// create a Statement object to execute the query with
			Statement stmt = conn.createStatement();
			results = stmt.executeQuery(query);
			return 1;
		}
		catch(Exception e)
		{
			System.out.println("Error in query()-> " + e);
			// failure!
			return 0;
		}
		
	}
	
	/* Try to close the connection.
	 * Return 0 upon failure. 
	 */
	public int disconnect() {
		connected = false;
		try
		{
			results.close();
			stmt.close();
			conn.close();
			return 1;
		}
		catch(Exception e)
		{
			System.out.println("Error in disconnect()-> " + e);
			// failure!
			return 0; 
		}
	}

}
